package com.banyuan.servlet.author;

import com.banyuan.dao.AuthorDao;
import com.banyuan.domain.Author;
import com.banyuan.utils.CommonUtils;
import com.banyuan.utils.DBUtils;
import com.banyuan.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/author/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String imageCode = req.getParameter("imageCode");


        // 1.判断取到的值是否为null或者去掉空格后是否为""
        if (CommonUtils.isEmpty(userName) || CommonUtils.isEmpty(password) ||
                CommonUtils.isEmpty(imageCode) ) {
            req.setAttribute("msg","输入项为空");
            req.getRequestDispatcher("/WEB-INF/pages/author/login.jsp").forward(req,resp);
            return;
            // 阻断代码运行
        }


        // 2.判断验证码是否正确

        HttpSession session = req.getSession();
        String imagecode = (String) session.getAttribute("IMAGECODE");
        if (!imageCode.equalsIgnoreCase(imagecode)) {
            req.setAttribute("msg","验证码不正确");
            req.getRequestDispatcher("/WEB-INF/pages/author/login.jsp").forward(req,resp);
            return;
            // 阻断代码运行
        }


        // 3.通过用户名和密码去查询一个用户的所有信息，去比较

        ResultSet resultSet = null;
        try {
            // 一定要传加密后的密码
             resultSet = AuthorDao.selectAuthorByUserNameAndPassword(userName, CommonUtils.calculateMD5(password));
            Author author = DBUtils.resultToBeanOne(resultSet, Author.class);
            if (author.getId() != null) {
                // 查出来的id不等于空的话，说明登陆成功
                session.setAttribute("author",author);
                System.out.println(author);
                // 将用户存到session
                //跳转到首页"/"--tomcat帮我们寻找index.jsp----IndexServlet--/WEB-INF/pages/index.jsp
                resp.sendRedirect(req.getContextPath());

            } else {
                req.setAttribute("msg","账号或者密码错误，请稍后再试");
                req.getRequestDispatcher("/WEB-INF/pages/author/login.jsp").forward(req,resp);
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.closeBy(resultSet);
        }

        // 登陆成功后，将用户存到session中

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
